/**
 * Created by chengming on 18/5/27.
 * version 1.0
 */
const BaseJsonAdapter = require('../base/BaseJsonAdapter');
const ArticleHrefAdapter = require('../ArticleHrefAdapter');
const iconv = require("iconv-lite");
const vm = require('vm');
const request = require('request-promise');
const logger = require('../../conf/logger');
const querystring = require("querystring")
const cheerio = require('cheerio');
const urlTool = require('url');

/**
 * 北京互金网
 * @type {module.Bjp2p}
 */
module.exports = class EnglishYangHang extends BaseJsonAdapter{

  async doRequest(){
    var form = {
      SearchTerm:'',
      Id:'{CE377CC8-BFBC-418B-B4D9-DBC1C64774A8}',
      PageSize: 15,
      'NewsTypesAvailable[]': 'e170e31a926f48d1a863ad8161ea771c',
      'NewsTypesAvailable[]': '09f8960ebc384e3589da5349744916ae',
      'NewsTypesAvailable[]': '65d34b0d42784c6bb1dd302c1ed63653',
      'NewsTypesAvailable[]': 'ce90163e489841e0b66d06243d35d5cb',
      'NewsTypesAvailable[]': 'f949c64a4c88448b9e269d10080b0987',
      'NewsTypesAvailable[]': '571948d14c6943f7b5b7748ad80bef29',
      Page: 1,
      Direction: 1,
      Grid: 'false',
      InfiniteScrolling: 'true'
    }

    var formData = querystring.stringify(form);
    var contentLength = formData.length;

    var options = {
      headers:{
        'Content-Length': contentLength,
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
      },
      // uri:'http://www.bjp2p.com.cn/supervise/queryNews4List',
      uri:this.requestUrl,
      body:formData,
      method:"POSt",
      encoding:null
    }
    let body = await request(options)
    return body;
  }

  async reqJson(){
    const body = await this.doRequest();
    let decodeBody = iconv.decode(body, this.encoding).toString();
    let data = JSON.parse(decodeBody);
    if( data['Results'] === null || data['Results'] === undefined ){
      return JSON.stringify([]);
    }else{
      let $ = cheerio.load(data['Results']);
      let contents = [];
      let rule = 'div.col3 a'
      $(rule).each( function() {
        let title = $(this).text();
        let href = $(this).attr('href');
        /* let title = $(this).text().trim();
           let href = '';
         if($(this).is('a') && $(this).attr('href')){
           href = urlTool.resolve(that.requestUrl, $(this).attr('href'));
         }*/

        if(title.length != 0 || href.length != 0){
          contents.push({
            title:title,
            href:href
          });
        }
      });
      return {data:contents}
    }
  }



}
